﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using BuXiaChu.OrderDishes.BLL.Utility;
using BuXiaChu.OrderDishes.BLL.Passport;
using BuXiaChu.OrderDishes.Model;

namespace BuXiaChu.OrderDishes.BLL.CookieManager
{
    public class AdminCookieManager
    {
        public static string CookieDomain
        {
            #region
            get
            {
                return ConfigurationManager.AppSettings["CookieDomain"] ?? "";
            }
            #endregion
        }

        public static string CookieName
        {
            #region
            get
            {
                return ConfigurationManager.AppSettings["CookieName"] ?? "";
            }
            #endregion
        }

        /// <summary>
        /// Cookie DES 8位密钥
        /// </summary>
        public static string SecretKey
        {
            get
            {
                var defaultKey = ConfigurationManager.AppSettings["CookieSecretKey"] ?? "enntrade";
                return defaultKey;
            }
        }

        public static string GetValueFromCookie(string key)
        {
            #region

            var request = HttpContext.Current.Request;
            var response = HttpContext.Current.Response;

            HttpCookie cookie = request.Cookies[CookieName];
            if (cookie != null && cookie.Values[key] != null)
            {
                return HttpUtility.UrlDecode(cookie.Values[key].Trim());//alter by lizunjing
            }

            return "";

            #endregion
        }

        /// <summary>
        /// 0:失败 1成功
        /// </summary>
        public static LoginResultEnum SignIn(string userName, string password)
        {
            #region
            if (string.IsNullOrEmpty(userName))
            {
                return LoginResultEnum.LoginNameIsEmpty;
            }

            if (string.IsNullOrEmpty(password))
            {
                return LoginResultEnum.PasspordIsEmpty;
            }
            var websiteId = new Guid(ConfigurationManager.AppSettings["WebsiteId"]);
            SysUserInfoModel userInfo = SysUserManager.GetSysUserInfoBy(userName, password, websiteId);
            if (userInfo.SystemUserId <= 0)
            {
                return LoginResultEnum.Failure;
            }

            EmployeesModel employee = EmployeesManager.GetEmployeesById(userInfo.EmployeeId);
            if (employee.Id <= 0)
            {
                return LoginResultEnum.NotExistEmploee;
            }

            string ipString = HttpContext.Current.Request.UserHostAddress;
            long ip = IPAddressUtility.ConvertToLong(ipString);
            Guid smartID = PassportManager.Instance.Create(userInfo.SystemUserId, ip);
            LoginSysUserInfo loginUserInfo = new LoginSysUserInfo();
            loginUserInfo.LoginName = userInfo.LoginName;
            loginUserInfo.LastLoginDate = userInfo.LastActiveDate;
            loginUserInfo.EmploeeId = userInfo.EmployeeId;
            loginUserInfo.JobTitle = CodeDictionary.Instance.GetCodeName(employee.JobTitle);
            loginUserInfo.Mobile = employee.MobileTelephone;
            loginUserInfo.RealName = employee.Name;

            if (!AddDataToCookie(smartID, userInfo.SystemUserId, loginUserInfo))
            {
                return LoginResultEnum.WriteDataToCookieFailure;
            }
            return LoginResultEnum.Success;
            #endregion
        }

        private static bool AddDataToCookie(Guid smartID, int userId, LoginSysUserInfo userInfo)
        {
            #region
            try
            {
                var request = HttpContext.Current.Request;
                var response = HttpContext.Current.Response;

                HttpCookie cookie = request.Cookies[CookieName];
                if (cookie != null)
                {
                    cookie.Values.Clear();
                    response.Cookies.Remove(CookieName);
                }
                else
                {
                    cookie = new HttpCookie(CookieName);
                }
                cookie.Domain = CookieDomain;


                cookie.Values.Add(CookieKeyConstants.SmartIDConstant, smartID.ToString());
                //cookie.Values.Add(CookieKeyConstants.UserIDConstant, userInfo.SystemUserId.ToString());
                response.Cookies.Add(cookie);
                HttpContext.Current.Session.Add(HttpContext.Current.Session.SessionID, userInfo);
                //角色
                //System.Web.Security.FormsAuthenticationTicket rolesTicket = new System.Web.Security.FormsAuthenticationTicket(
                //    1,
                //    user.UserID.ToString(),
                //    DateTime.Now,
                //    DateTime.Now.AddMinutes(30),
                //    false,
                //    roleString
                //    );

                //HttpCookie roleCookie = request.Cookies[RoleCookieName];
                //if (roleCookie != null)
                //{
                //    roleCookie.Values.Clear();
                //    response.Cookies.Remove(RoleCookieName);
                //}
                //else
                //{
                //    roleCookie = new HttpCookie(RoleCookieName);
                //}
                //roleCookie.Domain = CookieDomain;
                //roleCookie.Value = System.Web.Security.FormsAuthentication.Encrypt(rolesTicket);
                //response.Cookies.Add(roleCookie);
                System.Web.Security.FormsAuthentication.SetAuthCookie(userId.ToString(), false, "/");

                //System.Web.Security.FormsAuthentication.RedirectFromLoginPage(user.UserID.ToString(), false, "/");
                //System.Web.Security.FormsAuthentication.EnableCrossAppRedirects
                return true;
            }
            catch (Exception e)
            {
                ExceptionMessageManager.Record(e);
            }

            return false;

            #endregion
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void SignOut()
        {
            #region

            var request = HttpContext.Current.Request;
            var response = HttpContext.Current.Response;

            HttpCookie cookie = request.Cookies[CookieName];
            if (cookie != null)
            {
                cookie.Domain = CookieDomain;
                cookie.Values.Clear();
                cookie.Expires = DateTime.Now.AddYears(-10);
                response.Cookies.Add(cookie);
            }

            System.Web.Security.FormsAuthentication.SignOut();
            PassportManager.Instance.Remove(LoginSysUserInfo.Intance.SmartID);
            if (HttpContext.Current.Session != null)
            {
                HttpContext.Current.Session.Remove(HttpContext.Current.Session.SessionID);
            }

            #endregion
        }

        /// <summary>
        /// 产生machine key
        /// </summary>
        public static string GenerateMachineKey(int length)
        {
            #region
            var bytes = new byte[length];
            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            StringBuilder keyString = new StringBuilder();
            foreach (var b in bytes)
            {
                keyString.Append(string.Format("{0:X2}", b));
            }
            return keyString.ToString();
            #endregion
        }
    }
}
